package com.news.model.http.converter;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.news.base.BaseConverterFactory;
import com.news.base.HttpResponse;
import com.news.model.bean.Joke;
import com.news.util.LogUtil;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import okhttp3.ResponseBody;

/**
 * Created with Android Studio
 * User: ShiLiang
 * Date: 2017/3/2/0002
 * Project: TodayNews
 */

public class JokeConverterFactory extends BaseConverterFactory<ArrayList<Joke>> {

    private JokeConverterFactory() {
    }

    public static JokeConverterFactory create() {
        return new JokeConverterFactory();
    }

    @Override
    public HttpResponse<ArrayList<Joke>> convert(ResponseBody body) throws IOException {
        super.convert(body);
        HttpResponse<ArrayList<Joke>> ret = new HttpResponse<>();

        JsonParser parser = new JsonParser();
        final JsonElement root = parser.parse(new InputStreamReader(body.byteStream()));
        LogUtil.d("JokeConverterFactory", "convert root : " + root);
        ArrayList<Joke> jokes = null;
        if (root.isJsonObject()) {
            JsonObject object = root.getAsJsonObject();
            ret.setCode(object.get("error_code").getAsInt());
            JsonElement result = object.get("result");
            if (result.isJsonObject()) {
                JsonObject resultAsJsonObject = result.getAsJsonObject();
                JsonElement jsonElement = resultAsJsonObject.get("data");
                if (jsonElement.isJsonArray()) {
                    jokes = parseJokes(jsonElement);
                }
            } else if (result.isJsonArray()) {
                jokes = parseJokes(result);
            }
        }
        ret.setData(jokes);
        return ret;
    }

    private ArrayList<Joke> parseJokes(JsonElement jsonElement) {
        ArrayList<Joke> jokes = new ArrayList<>();
        JsonArray array = jsonElement.getAsJsonArray();
        Gson gson = new Gson();
        for (JsonElement element : array) {
            Joke joke = gson.fromJson(element, Joke.class);
            jokes.add(joke);
        }
        return jokes;
    }
}
